package com.zgl.gemduel.service;

import com.zgl.gemduel.model.RoomResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WebSocketService {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private RoomResourceNotificationService notificationService;

    @Autowired
    private RoomResourceService roomResourceService;

    // 存储客户端与房间的映射关系
    private final Map<String, String> clientRoomMap = new ConcurrentHashMap<>();

    /**
     * 客户端加入房间
     * @param sessionId 客户端会话ID
     * @param roomId 房间ID
     */
    public void joinRoom(String sessionId, String roomId) {
        if (roomId != null) {
            // 存储客户端与房间的映射关系
            clientRoomMap.put(sessionId, roomId);
            
            // 注意：这里我们不直接同步房间资源，而是通过RoomResourceService在适当的时候进行通知
        }
    }

    /**
     * 客户端离开房间
     * @param sessionId 客户端会话ID
     */
    public void leaveRoom(String sessionId) {
        // 移除客户端与房间的映射关系
        clientRoomMap.remove(sessionId);
    }

    /**
     * 同步房间资源给指定客户端
     * @param sessionId 客户端会话ID
     * @param roomResource 房间资源
     */
    public void syncRoomResource(String sessionId, RoomResource roomResource) {
        if (roomResource != null) {
            // 发送房间资源更新消息给指定客户端
            messagingTemplate.convertAndSendToUser(sessionId, "/topic/room_resource_update", roomResource);
        }
    }

    /**
     * 同步房间资源给房间内的所有客户端
     * @param roomId 房间ID
     * @param roomResource 房间资源
     */
    public void syncRoomResourceToAll(String roomId, RoomResource roomResource) {
        notificationService.notifyRoomResourceUpdate(roomId, roomResource);
    }

    /**
     * 处理客户端发送的指令
     * @param roomId 房间ID
     * @param command 指令数据
     */
    public void handleGameCommand(String roomId, Map<String, Object> command) {
        String commandType = (String) command.get("command");
        Map<String, Object> payload = (Map<String, Object>) command.get("payload");

        if (commandType != null) {
            // 处理指令（具体游戏逻辑待后续补充）
            processGameCommand(roomId, commandType, payload);
            
            // 注意：房间资源的同步现在由RoomResourceService负责
        }
    }

    /**
     * 处理游戏指令（具体逻辑待后续补充）
     * @param roomId 房间ID
     * @param commandType 指令类型
     * @param payload 数据负载
     */
    private void processGameCommand(String roomId, String commandType, Map<String, Object> payload) {
        // TODO: 实现具体的游戏指令处理逻辑
        System.out.println("Processing command: " + commandType + " for room: " + roomId);
        
        // 根据不同的指令类型进行处理
        switch (commandType) {
            case "buy_card":
                // 处理购买卡片指令
                processBuyCardCommand(roomId, payload);
                break;
            case "buy_card_with_gems":
                // 处理购买卡片指令（支持玩家选择宝石作为支付筹码）
                processBuyCardWithGemsCommand(roomId, payload);
                break;
            case "reserve_card":
                // 处理保留卡片指令
                processReserveCardCommand(roomId, payload);
                break;
            case "pass_turn":
                // 处理回合结束指令
                processStartNewRoundCommand(roomId, payload);
                break;
            case "start_game":
                // 处理开始游戏指令
                processStartGameCommand(roomId);
                break;
            case "use_privilege":
                // 处理使用特权指令
                processUsePrivilegeCommand(roomId, payload);
                break;
            case "gain_privilege":
                // 处理获取特权指令
                processGainPrivilegeCommand(roomId, payload);
                break;
            case "take_gems":
                // 处理拿取宝石指令
                processTakeGemsCommand(roomId, payload);
                break;
            case "start_new_round":
                // 处理开始新回合指令
                processStartNewRoundCommand(roomId, payload);
                break;
            case "play_another_round":
                // 处理再来一轮指令
                processPlayAnotherRoundCommand(roomId, payload);
                break;
            case "change_card_color":
                // 处理卡片变色指令
                processChangeCardColorCommand(roomId, payload);
                break;
            case "take_gem_from_opponent":
                // 处理获取对方玩家宝石指令
                processTakeGemFromOpponentCommand(roomId, payload);
                break;
            case "refill_gem_board":
                // 处理补充宝石盘指令
                processRefillGemBoardCommand(roomId, payload);
                break;
            case "player_ready":
                // 处理玩家准备/取消准备指令
                processPlayerReadyCommand(roomId, payload);
                break;
            default:
                // 未知指令
                System.out.println("Unknown command: " + commandType);
                break;
        }
    }

    /**
     * 处理开始游戏指令
     * @param roomId 房间ID
     */
    private void processStartGameCommand(String roomId) {
        System.out.println("Starting game for room: " + roomId);
        // 调用RoomResourceService来处理开始游戏逻辑
        roomResourceService.startGame(roomId);
    }

    /**
     * 处理使用特权指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processUsePrivilegeCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing use privilege command for room: " + roomId);
        
        // 从payload中获取玩家IP和宝石位置索引
        String playerIp = (String) payload.get("playerIp");
        Integer gemPositionIndex = (Integer) payload.get("gemPositionIndex");
        
        if (playerIp != null && gemPositionIndex != null) {
            // 调用RoomResourceService来处理使用特权逻辑
            roomResourceService.usePrivilegeToExchangeGem(roomId, playerIp, gemPositionIndex);
        }
    }

    /**
     * 处理获取特权指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processGainPrivilegeCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing gain privilege command for room: " + roomId);
        
        // 从payload中获取玩家IP
        String playerIp = (String) payload.get("playerIp");
        
        if (playerIp != null) {
            // 调用RoomResourceService来处理获取特权逻辑
            roomResourceService.gainPrivilege(roomId, playerIp);
        }
    }

    /**
     * 处理拿取宝石指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processTakeGemsCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing take gems command for room: " + roomId);
        
        // 从payload中获取玩家IP和宝石位置索引列表
        String playerIp = (String) payload.get("playerIp");
        List<Integer> gemPositionIndices = (List<Integer>) payload.get("gemPositionIndices");
        
        if (playerIp != null && gemPositionIndices != null) {
            // 调用RoomResourceService来处理拿取宝石逻辑
            roomResourceService.takeGems(roomId, playerIp, gemPositionIndices);
        }
    }

    /**
     * 处理购买卡片指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processBuyCardCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing buy card command for room: " + roomId);
        
        // 从payload中获取玩家IP和卡片ID
        String playerIp = (String) payload.get("playerIp");
        String cardId = (String) payload.get("cardId");
        
        if (playerIp != null && cardId != null) {
            // 调用RoomResourceService来处理购买卡片逻辑
            roomResourceService.buyCard(roomId, playerIp, cardId);
        }
    }

    /**
     * 处理保留卡片指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processReserveCardCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing reserve card command for room: " + roomId);
        
        // 从payload中获取玩家IP、卡片ID和黄金宝石位置
        String playerIp = (String) payload.get("playerIp");
        String cardId = (String) payload.get("cardId");
        Integer goldGemPosition = (Integer) payload.get("goldGemPosition");
        
        if (playerIp != null && cardId != null) {
            // 调用RoomResourceService来处理保留卡片逻辑，并传递黄金宝石位置
            roomResourceService.reserveCard(roomId, playerIp, cardId, goldGemPosition);
        }
    }

    /**
     * 处理开始新回合指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processStartNewRoundCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing start new round command for room: " + roomId);
        
        // 调用RoomResourceService来处理开始新回合逻辑
        roomResourceService.startNewRound(roomId);
    }

    /**
     * 处理再来一轮指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processPlayAnotherRoundCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing play another round command for room: " + roomId);
        
        // 调用RoomResourceService来处理再来一轮逻辑
        roomResourceService.playAnotherRound(roomId);
    }

    /**
     * 处理卡片变色指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processChangeCardColorCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing change card color command for room: " + roomId);
        
        // 从payload中获取玩家IP、卡片ID和颜色
        String playerIp = (String) payload.get("playerIp");
        String cardId = (String) payload.get("cardId");
        String color = (String) payload.get("color");
        
        if (playerIp != null && cardId != null && color != null) {
            // 调用RoomResourceService来处理卡片变色逻辑
            roomResourceService.changeCardColor(roomId, playerIp, cardId, color);
        }
    }

    /**
     * 处理获取对方玩家宝石指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processTakeGemFromOpponentCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing take gem from opponent command for room: " + roomId);
        
        // 从payload中获取玩家IP、目标玩家IP和宝石颜色
        String playerIp = (String) payload.get("playerIp");
        String targetPlayerIp = (String) payload.get("targetPlayerIp");
        String gemColor = (String) payload.get("gemColor");
        
        if (playerIp != null && targetPlayerIp != null && gemColor != null) {
            // 调用RoomResourceService来处理获取对方玩家宝石逻辑
            roomResourceService.takeGemFromOpponent(roomId, playerIp, targetPlayerIp, gemColor);
        }
    }

    /**
     * 处理补充宝石盘指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processRefillGemBoardCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing refill gem board command for room: " + roomId);
        
        // 从payload中获取当前玩家IP
        String playerIp = (String) payload.get("playerIp");
        
        // 调用RoomResourceService来处理补充宝石盘逻辑
        roomResourceService.refillGemBoard(roomId);
    }

    /**
     * 处理玩家准备/取消准备指令
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processPlayerReadyCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing player ready command for room: " + roomId);
        
        // 从payload中获取玩家IP
        String playerIp = (String) payload.get("playerIp");
        
        if (playerIp != null) {
            // 调用RoomResourceService来处理玩家准备/取消准备逻辑（直接切换状态）
            roomResourceService.togglePlayerReady(roomId, playerIp);
        }
    }

    /**
     * 处理购买卡片指令（支持玩家选择宝石作为支付筹码）
     * @param roomId 房间ID
     * @param payload 数据负载
     */
    private void processBuyCardWithGemsCommand(String roomId, Map<String, Object> payload) {
        System.out.println("Processing buy card with gems command for room: " + roomId);
        
        // 从payload中获取玩家IP、卡片ID和宝石ID列表
        String playerIp = (String) payload.get("playerIp");
        String cardId = (String) payload.get("cardId");
        List<String> gemIds = (List<String>) payload.get("gemIds");
        
        if (playerIp != null && cardId != null && gemIds != null) {
            // 调用RoomResourceService来处理购买卡片逻辑（使用选择的宝石）
            roomResourceService.buyCardWithGems(roomId, playerIp, cardId, gemIds);
        }
    }
}